package cn.lili.common.utils;

import cn.lili.cache.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author xiangqian
 * @Date 2023/10/5 14:55
 */
@Component
@Slf4j
public class BlindboxCodeUtil {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取所有奖卷号码
     *
     * @param maxNumber 生成的最大数值
     */
    public static List<String> generateCodeAll(Integer maxNumber) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < maxNumber; i++) {
            String sequence = String.format("%0" + String.valueOf(maxNumber).length() + "d", i); // 格式化为4位数，不足的补0
            list.add(sequence);
        }
        return list;
    }

    /**
     * 随机获取奖卷
     *
     * @param numbers 所有奖卷
     */
    public static String getRandomNumber(List<String> numbers) {
        Random random = new Random();
        int index = random.nextInt(numbers.size()); // 生成0到numbers.size()-1之间的随机索引
        return numbers.get(index);
    }


    /**
     * @param goodsId   商品ID
     * @param ruleId    规则ID
     * @param maxNumber 最大次数
     */
    public synchronized String generateCouponsOne(String goodsId, String ruleId, Integer maxNumber) {
        StringBuffer key = new StringBuffer();
        key.append(goodsId);
        key.append("_");
        key.append(ruleId);

        //查询缓存中未分配的奖卷
        List<String> allNumber = redisUtil.get(key.toString(), List.class);
        String keyLock = redisUtil.get(key+"_key", String.class);
        if ((allNumber == null || allNumber.size() ==0) && StringUtils.isEmpty(keyLock)) {
            log.info("生成所有将卷");
            //如果没有设置，则设置
            allNumber = generateCodeAll(maxNumber);
            redisUtil.set(key.toString(), allNumber);
            redisUtil.set(key+"_key", "1");
        }
        log.info("allNumber-begin---" + allNumber.size());

        //获取将卷
        String code = getRandomNumber(allNumber);
        log.info("allNumber-code---" + code);

        //重置缓存
        allNumber.remove(code);
        redisUtil.set(key.toString(),allNumber);

        log.info("allNumber-end---" + allNumber.size());
        return code;
    }
}
